package com.centerm.demo;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.centerm.bluetooth.ibridge.BluetoothIBridgeDevice;
import com.centerm.bluetooth.lkl.SwiperController;
import com.centerm.bluetooth.lkl.demo.R;
import com.centerm.bluetooth.lkl.listener.ISwiperListener;
import com.centerm.bluetooth.lklcommon.mode.Track;
import com.centerm.util.Logger;

import java.io.IOException;


public class MainActivity extends AppCompatActivity implements MessageDialog.ISureListener, BluetoothDialog.IItemSelListener {

    private TextView txtvw;
    private EditText edtxtMoney;
    private BluetoothDialog bluetoothDialog;
    private MessageDialog messageDialog;
    private SwiperController swiperController;
    private CheckBox trackCard, icCard, nfCard;
    private ScrollView scrvw;
    private AlertDialog alertDialog;
    private static Handler handler = new Handler();
    private boolean showOnce;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showOnce = true;
        txtvw = (TextView) findViewById(R.id.txtvw);
        bluetoothDialog = new BluetoothDialog(this);
        bluetoothDialog.setItemSelListener(this);
        messageDialog = new MessageDialog(this);
        messageDialog.setSureListener(this);
        swiperController = SwiperController.getInstance(getApplicationContext());
        swiperController.setSwiperListener(new SwiperImp());
        bluetoothDialog.btnReSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bluetoothDialog.clear();
                swiperController.startDiscovery(30);
            }
        });
        trackCard = (CheckBox) findViewById(R.id.trackCard);
        icCard = (CheckBox) findViewById(R.id.icCard);
        nfCard = (CheckBox) findViewById(R.id.nfCard);
        edtxtMoney = (EditText) findViewById(R.id.edtxtMoney);
        edtxtMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (!TextUtils.isEmpty(text) && text.length() > 0) {

                    if (text.charAt(0) == '0') {
                        if (text.length() >= 2) {
                            text = text.substring(1);
                        } else text = "";
                        edtxtMoney.setText(text);
                    }
                }
            }
        });
        CheckBox chboxLogcat = (CheckBox) findViewById(R.id.chboxLogcat);
        chboxLogcat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Logger.setDEBUG(isChecked, isChecked);
            }
        });
        alertDialog = new AlertDialog.Builder(this).setTitle("权限被拒绝").setMessage("\n所需要手动修改说明:\n 1.定位权限开启允许\n 2.蓝牙权限开启允许").setPositiveButton("手动修改权限", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                appDetail(null);
            }
        }).setNegativeButton("取消", null).setCancelable(false).create();
        scrvw = (ScrollView) findViewById(R.id.scrvw);
        Logger.i(" == showOnce == " + showOnce);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (showOnce) {
            showOnce = false;
            int permision = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (permision != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            } else {
                onSeach(null);
            }
            Logger.i(" == showOnce == " + showOnce);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Build.VERSION.SDK_INT >= 23) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        onSeach(null);
                    }
                }, 200);
            } else {
                alertDialog.show();
            }
        } else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    onSeach(null);
                }
            }, 200);

        }
    }

    public void onSeach(View v) {
        BluetoothIBridgeDevice device = bluetoothDialog.getSel();
        if (device != null && device.isConnected()) {
            try {
                swiperController.reset();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            swiperController.disconnectBT(device);
        }
        bluetoothDialog.btnReSearch.setText("正在搜索");
        bluetoothDialog.show();
        swiperController.startDiscovery(10);
    }

    public void resetSDK(View v) {
        swiperController.resetSDKStatus();
    }

    public void reset(View v) {
        try {
            swiperController.reset();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onConnect(View v) {
        BluetoothIBridgeDevice device = bluetoothDialog.getSel();
        if (device != null) {
            if (!device.isConnected())
                swiperController.connectBT(device);
            else {
                Toast.makeText(this, "设备已连接", Toast.LENGTH_LONG).show();
            }
        }
    }

    public void onStartTrade(View v) {
        BluetoothIBridgeDevice device = bluetoothDialog.getSel();
        if (device == null || !device.isConnected()) {
            Toast.makeText(this, "请先连接蓝牙设备!", Toast.LENGTH_LONG).show();
            return;
        }
        int mode = 0;
        if (trackCard.isChecked()) {
            mode = mode | 0x01;
        }
        if (icCard.isChecked()) {
            mode = mode | 0x02;
        }
        if (nfCard.isChecked()) {
            mode = mode | 0x04;
        }

        if (mode == 0) {
            Toast.makeText(this, "请选择模拟交易卡类型方式", Toast.LENGTH_LONG).show();
            return;
        }

        String money = edtxtMoney.getText().toString();
        if (TextUtils.isEmpty(money))
            money = "1000000";

        try {
            boolean res = swiperController.startSwiper(mode, 20, money, "模拟交易", null);
            if (res) {
                logsBuffer.append("等待刷卡").append("\n");
            } else {
                logsBuffer.append("设备忙").append("\n");
            }
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodTools.HideKeyboard(v);
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public void clearLog(View v) {
        if (logsBuffer.length() > 0)
            logsBuffer.delete(0, logsBuffer.length() - 1);
        txtvw.setText(logsBuffer.toString());
        scroll2Bottom();
    }

    public void appDetail(View v) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(localIntent);
    }

    private StringBuffer logsBuffer = new StringBuffer();

    @Override
    public void onSure() {
        bluetoothDialog.dismiss();
        messageDialog.dismiss();
        onConnect(null);
    }

    @Override
    public void onItemClick(BluetoothIBridgeDevice device) {
        messageDialog.setMessage("选择蓝牙名：" + device.getDeviceName() + "\n蓝牙地址：" + device.getDeviceAddress());
        messageDialog.show();
    }

    public void scroll2Bottom() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (txtvw == null || txtvw == null) {
                    return;
                }
                // 内层高度超过外层
                int offset = txtvw.getMeasuredHeight()
                        - scrvw.getMeasuredHeight();
                if (offset < 0) {
                    offset = 0;
                }
                scrvw.smoothScrollTo(0, offset);
            }
        }, 100);


    }


    private class SwiperImp implements ISwiperListener {

        @Override
        public void onConnected() {
            logsBuffer.append("蓝牙已经连接").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onDisconnected() {
            logsBuffer.append("蓝牙断开连接").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onConnectFailure() {
            logsBuffer.append("蓝牙连接失败").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onFound(BluetoothIBridgeDevice device) {
            if (device != null && !TextUtils.isEmpty(device.getDeviceName()))
                bluetoothDialog.add(device);
        }

        @Override
        public void onFoundEnd() {
            Logger.i(" == onFoundEnd ==");
            bluetoothDialog.btnReSearch.setEnabled(true);
            bluetoothDialog.btnReSearch.setText("重新搜索");
            scroll2Bottom();
        }

        @Override
        public void onTradeSuc(Track track) {
            Logger.i(track);
            logsBuffer.append("卡号：").append("" + track.getPan().replace("f", "").replace("F", "").replace("E", "*")).append("\n");
            logsBuffer.append("密码：").append(track.getPinBlock()).append("\n");
            if (!TextUtils.isEmpty(track.getData55())) {
                logsBuffer.append("55域数据：").append(track.getData55()).append("\n");
            } else if (!TextUtils.isEmpty(track.getTrack2()))
                logsBuffer.append("磁道数据：").append(track.getTrack2()).append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onSwiperCancel() {
            logsBuffer.append("取消刷卡").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onSwiperTimeout() {
            logsBuffer.append("刷卡超时").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onSwiperError() {
            logsBuffer.append("刷卡失败").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onInputWaiter() {
            logsBuffer.append("等待输密").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onInputCancel() {
            logsBuffer.append("输密取消").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onInputTimeout() {
            logsBuffer.append("输密超时").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onPBOCError() {
            logsBuffer.append("执行PBOC或QPBOC失败").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onTimeout() {
            logsBuffer.append("命令没返回").append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }

        @Override
        public void onError(String msg) {
            logsBuffer.append("命令响应出错：").append(msg).append("\n");
            txtvw.setText(logsBuffer.toString());
            scroll2Bottom();
        }
    }

}
